package com.ohuang.wallpapermanager.wallpaper

import android.content.Context
import com.ohuang.wallpapermanager.WallPaperManager
import com.ohuang.wallpapermanager.compose.tryCatch
import com.ohuang.wallpapermanager.config.LocalConfig
import com.ohuang.wallpapermanager.config.LogConfig
import com.ohuang.wallpapermanager.data.TimeData
import com.ohuang.wallpapermanager.data.TimeFrameData
import com.ohuang.wallpapermanager.data.WallPaperInfoData
import com.ohuang.wallpapermanager.data.WallPaperInfoTimeRuleData
import com.ohuang.wallpapermanager.data.WallPaperInfoWeekData
import com.ohuang.wallpapermanager.repository.WallPaperInfoRepository
import com.ohuang.wallpapermanager.util.TimeUtil

class CarouselWallPaper(private val isLock: Boolean) {
    private var wallPaperInfoRepository = WallPaperInfoRepository(isLock)
    private val dTime: Long = 60_000 // 补偿时间
    fun run(context: Context) {
        if (!wallPaperInfoRepository.getConfig().isCarouselEnable) {
            return
        }
        val wallPaperInfoList = wallPaperInfoRepository.getWallPaperInfoList()
        val currentTimeMillis = System.currentTimeMillis()
        val matchTimeList = wallPaperInfoList.filter { it.timeRule.isMatch(currentTimeMillis) }
        val data = matchTimeList.firstOrNull() { it.isForceShow }
        if (data != null) {
            setForceWall(context, data)
        } else {
            randomWall(context, matchTimeList.filter { !it.isForceShow })
        }
    }

    private fun randomWall(context: Context, wallPaperInfoList: List<WallPaperInfoData>) {
        if (wallPaperInfoList.isEmpty()) {
            return
        }
        if ((System.currentTimeMillis() - wallPaperInfoRepository.getConfig().lastUpdateTimeRandom)
            < (wallPaperInfoRepository.getConfig().minRandomInterval - dTime)
        ) {
            return
        }
        val data = wallPaperInfoList.random()
        if (wallPaperInfoRepository.getConfig().lastUpdateWallId != data.id) {
            setWallPaper(context, data.filePath)
            val currentTimeMillis = System.currentTimeMillis()
            wallPaperInfoRepository.getConfig().lastUpdateWallId = data.id
            wallPaperInfoRepository.getConfig().lastUpdateTimeRandom = currentTimeMillis
            wallPaperInfoRepository.getConfig().lastUpdateTime = currentTimeMillis
            LogConfig.appLog("随机设置${if (isLock) "锁屏" else "桌面"}")
        }
    }

    private fun setForceWall(context: Context, data: WallPaperInfoData) {
        if (data.filePath.isEmpty()) {
            return
        }
        if (wallPaperInfoRepository.getConfig().lastUpdateWallId != data.id) {
            setWallPaper(context, data.filePath)
            wallPaperInfoRepository.getConfig().lastUpdateWallId = data.id
            wallPaperInfoRepository.getConfig().lastUpdateTime = System.currentTimeMillis()
            LogConfig.appLog("强制设置${if (isLock) "锁屏" else "桌面"}")
        }
    }


    private fun setWallPaper(context: Context, fileName: String) {
        if (fileName.isEmpty()) {
            return
        }
        tryCatch {
            if (LocalConfig.isUseWallPaperService) { //动态壁纸方案启动
                if (isLock) {
                    LocalConfig.useWallPaperImagePathLock = fileName
                } else {
                    LocalConfig.useWallPaperImagePath = fileName
                }
            } else {   //静态壁纸方案启动
                WallPaperManager.setWallPaperForFile(fileName, context, isLock)
            }
        }
    }


}

fun WallPaperInfoTimeRuleData.isMatch(time: Long): Boolean {
    return this.week.isMatch(time) && this.timeFrame.isMatch(time)
}

fun WallPaperInfoWeekData.isMatch(time: Long): Boolean {
    if (anyDay) {
        return true
    }
    val week = TimeUtil.getWeek(time)
    return weekDayList.contains(week)
}

/**
 * 判断时间是否在时间段内
 */
fun TimeFrameData.isMatch(time: Long): Boolean {
    if (antTimeFrame) {
        return true
    }

    return isMatch(
        TimeData(
            hour = TimeUtil.getHour(time),
            minute = TimeUtil.getMinute(time)
        )
    )
}

fun TimeFrameData.isMatch(time: TimeData): Boolean {
    if (startTime == endTime) {
        // 全时间段
        return true
    }
    if (startTime.hour > endTime.hour || (startTime.hour == endTime.hour && startTime.minute > endTime.minute)) {
        // 跨天
        return (time.hour > startTime.hour || time.hour < endTime.hour) ||
                (time.hour == startTime.hour && time.minute >= startTime.minute) ||
                (time.hour == endTime.hour && time.minute <= endTime.minute)
    }
    // 正常情况
    return (time.hour >= startTime.hour && time.hour <= endTime.hour) &&
            (time.hour != startTime.hour || time.minute >= startTime.minute) &&
            (time.hour != endTime.hour || time.minute <= endTime.minute)
}


